<template>
  <div class="purchase">
    <!-- 搜索 -->
    <div class="purchase-serch">
      <el-form ref="formRef">
        <div class="form-content">
          <div class="left">
            <el-form-item label="采购状态" label-width="120">
              <el-select v-model="data.forms['businessState']">
                <el-option v-for="item in data.businessStateList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="仓库选择" label-width="120">
              <el-select v-model="data.forms['receivingWarehouseId']">
                <el-option v-for="item in data.listByTenantIdList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="关联订单编码" label-width="120">
              <el-input v-model="data.forms['orderCode']" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="创建时间" label-width="120">
              <el-date-picker
                v-model="data.forms['createTime']"
                value-format="YYYY-MM-DD hh:mm:ss"
                type="daterange"
                placeholder="日期"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                style="width: 40%"
              />
              <el-button @click="handelClickToday(1)">今天</el-button>
              <el-button @click="handelClickYersToday(1)">昨天</el-button>
              <el-button @click="handelClickSevenDay(1)">近七天</el-button>
            </el-form-item>
            <el-form-item label="采购编码" label-width="120">
              <el-input v-model="data.forms['purchaseOrderNo']" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="收款账户" label-width="120">
              <el-input v-model="data.forms['payAccount']" placeholder="请输入"></el-input>
            </el-form-item>
          </div>
          <div class="right">
            <el-form-item label="付款状态" label-width="120">
              <el-select v-model="data.forms['payStatus']">
                <el-option v-for="item in data.payStatusList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建人" label-width="120">
              <el-select v-model="data.forms['createId']">
                <el-option v-for="item in data.createIdList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="供应商名称" label-width="120">
              <el-input v-model="data.forms['factoryName']" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="到货时间" label-width="120">
              <el-date-picker
                v-model="data.forms['expectedDeliveryTime']"
                value-format="YYYY-MM-DD hh:mm:ss"
                type="daterange"
                placeholder="日期"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                style="width: 40%"
              />
              <el-button @click="handelClickToday(2)">今天</el-button>
              <el-button @click="handelClickYersToday(2)">昨天</el-button>
              <el-button @click="handelClickSevenDay(2)">近七天</el-button>
            </el-form-item>
            <el-form-item label="订单金额" label-width="120">
              <div class="dd-price-wrap">
                <el-select v-model="data.forms['amountType']" clearable>
                  <el-option v-for="item in data.priceStatusList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <div class="price-range">
                  <el-input
                    :min="0"
                    type="number"
                    v-model="data.forms.minAmount"
                    placeholder=""
                    clearable
                    :disabled="!data.forms['amountType']"
                  />
                  <span> - </span>
                  <el-input
                    :min="0"
                    type="number"
                    v-model="data.forms.maxAmount"
                    placeholder=""
                    clearable
                    :disabled="!data.forms['amountType']"
                  />
                </div>
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div class="serch">
        <el-button type="primary" :icon="Search" @click.prevent="handelClickSerch">查询</el-button>
        <el-button type="primary" plain :icon="RefreshLeft" @click="resetForm">重置</el-button>
      </div>
    </div>
    <!-- 新建 -->
    <div class="purchase-add">
      <div>
        <el-button type="primary" @click="handelClickNewAdd">新建采购单</el-button>
        <el-button type="primary" :loading="downloadLoading" @click="clickDdownload">导出</el-button>
      </div>
      <div>
        <el-input
          style="max-width: 800px; width: 300px"
          v-model="data.forms['customer']"
          placeholder="请输入客户名称、手机号"
          class="input-with-select"
          @change="handelClickSerch"
        >
          <!-- <template #prepend>
            <el-select placeholder="请选择" style="width: 115px" v-model="data.slectValue">
              <el-option label="全部" value="1" />
              <el-option label="姓名" value="2" />
              <el-option label="手机号" value="3" />
            </el-select>
          </template> -->
        </el-input>
        <el-button type="primary" plain :icon="RefreshLeft" @click="resetForm">重置</el-button>
      </div>
    </div>
    <!-- 数据表格 -->
    <div class="purchase-tabel">
      <el-table :data="data.list" v-if="data.list?.length > 0" style="width: 100%" class="jzt-table" stripe>
        <el-table-column prop="createTime" label="创建日期" width="200" />
        <el-table-column prop="expectedDeliveryTime" label="到货日期" width="200" />
        <el-table-column prop="purchaseOrderNo" label="采购编码" width="200" />
        <el-table-column prop="anotherName" label="供应商名称" width="120" />
        <!-- <el-table-column prop="address" label="产品类别" width="600" /> -->
        <el-table-column prop="customer" label="关联客户" width="200" />
        <el-table-column label="付款计划" width="200">
          <template #default="scope">
            <div
              v-if="scope.row.payPlanList && scope.row.payPlanList.length > 0"
              style="cursor: pointer"
              @click="openPlanNodes(scope.row)"
            >
              一期款项-接采购单即付款：{{ scope.row.payPlanList[0].payableAmount }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="orderCode" label="关联订单编码" width="220" />
        <el-table-column prop="payableTotalAmount" label="应付金额" width="120" />
        <el-table-column prop="currentPayableAmount" label="本次应付金额" width="120">
          <template #default="scope">
            <p>{{ scope.row.currentPayableAmount || "-" }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="actualTotalAmount" label="实付金额" width="120" />

        <el-table-column prop="productTotalAmount" label="商品总计金额" width="220" />
        <el-table-column prop="orderTime" label="提交时间" width="220" />
        <!-- <el-table-column prop="expectedDeliveryTime" label="到货时间" width="120" /> -->
        <el-table-column prop="remark" label="备注" width="224">
          <template #default="scope">
            <!-- <el-input v-model="scope.row.remark" placeholder="请输入备注"></el-input> -->
            <RemarkEditor v-model="scope.row.remark" :isEdit="false" />
          </template>
        </el-table-column>
        <!-- <el-table-column prop="otherFee" label="其他金额" width="120" />
        <el-table-column prop="discountAmount" label="优惠金额" width="120" />
        <el-table-column prop="remainTotalAmount" label="未收金额" width="120" /> -->
        <el-table-column prop="businessState" label="采购状态" width="120">
          <template #default="scope">
            <span :style="{ color: statusColor(scope.row.businessState) }">
              {{ showStatus(scope.row.businessState) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="payStatus" label="付款状态" width="120">
          <template #default="scope">
            <p
              class="pay_status"
              :style="{
                color: payStatusColor(scope.row.payStatus)[0],
                background: payStatusColor(scope.row.payStatus)[1],
                textAlign: 'center'
              }"
            >
              {{ scope.row.payStatus === 1 ? "待支付" : scope.row.payStatus === 2 ? "部分支付" : "已支付" }}
            </p>
          </template>
        </el-table-column>
        <el-table-column prop="payAccount" label="收款账户信息" width="220">
          <template #default="scope">
            <p v-if="scope.row.payAccountName && scope.row.payDictName && scope.row.payAccount">
              {{ scope.row.payAccountName + "：" + scope.row.payDictName + "：" + scope.row.payAccount }}
            </p>
            <p v-else-if="scope.row.payDictName && scope.row.payAccount">
              {{ scope.row.payDictName + "：" + scope.row.payAccount }}
            </p>
            <p v-else>-</p>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="zip" label="关联订单编码" width="120" /> -->
        <el-table-column fixed="right" label="操作" min-width="200">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleClickDetail(scope.row)"> 清单 </el-button>
            <el-button
              v-if="scope.row.isProduceConfirmState === 2"
              link
              type="primary"
              size="small"
              @click="handleProduction(scope.row, 1)"
            >
              生产完成
            </el-button>
            <el-button
              v-if="scope.row.isDistributeConfirmState === 4"
              link
              type="primary"
              size="small"
              @click="handleProduction(scope.row, 2)"
            >
              配送完成确认
            </el-button>
            <el-button
              v-if="scope.row.isSelfPickupState === 3"
              link
              type="primary"
              size="small"
              @click="handleProduction(scope.row, 3)"
            >
              已完成提货
            </el-button>
            <el-button
              v-if="scope.row.isInstallConfirmState === 2"
              link
              type="primary"
              size="small"
              @click="handleProduction(scope.row, 4)"
            >
              安装完成确认
            </el-button>

            <el-button
              link
              type="primary"
              v-if="scope.row.businessState == 1 ? false : scope.row.businessState == 3 ? false : true"
              size="small"
              @click="handelClickChange(scope.row)"
            >
              详情
            </el-button>
            <el-button
              link
              type="primary"
              size="small"
              v-if="scope.row.showCancelButton === 1"
              @click="
                () => {
                  currCelObj = scope.row;
                  _isOpenDel = true;
                }
              "
            >
              撤销
            </el-button>
            <el-button
              link
              type="primary"
              size="small"
              @click="handelClickChange(scope.row)"
              v-if="[2, 4, 5, 6, 7, 8, 9, 10, 20, 21].includes(scope.row.businessState) ? false : true"
              >修改</el-button
            >
            <el-popconfirm title="确定关闭吗?" @confirm="handelClickCloseOder(scope.row)">
              <template #reference>
                <el-button
                  link
                  type="primary"
                  size="small"
                  v-if="scope.row.businessState == 3 || scope.row.businessState == 20 ? true : false"
                  >关闭</el-button
                >
              </template>
            </el-popconfirm>
            <el-button link type="primary" size="small" v-if="isPaymentVisible(scope.row)" @click="handelClickChange(scope.row)"
              >去付款</el-button
            >
            <el-button link type="primary" size="small" v-if="isPaymentVisible(scope.row)" @click="handelClickChange(scope.row)"
              >继续付款</el-button
            >
          </template>
        </el-table-column>
        <template #empty>
          <div style="text-align: center; padding: 20px">
            <el-empty description="这里暂时什么都没有" />
          </div>
        </template>
      </el-table>
      <el-empty v-else description="这里暂时什么都没有"></el-empty>
      <div class="pag-ation">
        <el-pagination
          :page-sizes="[10, 20, 30, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="data.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <!-- 撤销 二次确认 -->
      <ActionSubmitDialog
        v-model:isOpen="_isOpenDel"
        :title="'温馨提示'"
        :message="'订单已处于接单状态，撤销后，当前采购单将作废处理，请谨慎操作！'"
        :submitBtnText="'确认撤销'"
        @submit="returnSubmitDel"
      />
    </div>

    <!-- 抽屉 -->
    <!-- 发货确认、自提货完成确认、安装完成确认、配送完成确认-->
    <editorDialog
      v-model:isOpen="_isOpenEditor"
      :title="editorDialogInfo.title"
      :status="editorDialogInfo.status"
      :remark="editorDialogInfo.remark"
      :refuseReason="editorDialogInfo.refuseReason"
      :refuseRemark="editorDialogInfo.refuseRemark"
      :submitBtnText="editorDialogInfo.submitBtnText"
      :cancelBtnText="editorDialogInfo.cancelBtnText"
      @submit="submitDrawer"
      @refuse="refuseDrawer"
      @close="closeDrawer"
    />

    <!-- 通过审核二次确认-弹窗 -->
    <el-dialog v-model="adoptDialog" title="" center align-center width="500">
      <div class="adopt-dialog">
        请仔细核对，或者致电联系，确保您的订单商品已{{ editorDialogInfo.title }}一旦确认通过后，此操作不支持逆向操作，请谨慎操作！
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="adoptDialog = false">取消</el-button>
          <el-button type="primary" @click="adoptDialogSubmit"> 确认通过 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 拒绝-弹窗 -->
    <RefuseDialog v-model:isOpen="refuseDialog" :options="refuseOptions" @submit="refuseSubmit" @close="refuseClose" />

    <!-- 订单付款计划节点明细-弹窗 -->
    <el-dialog class="plan-nodes" v-model="planNodes" title="订单付款计划节点明细" width="1200" align-center>
      <div class="plan-nodes-top">
        <div class="money-box">
          <div>
            订单总额应收金额：<span class="money"> ¥{{ currentPlanRow.payableTotalAmount }}</span>
          </div>
          <div>
            税额：<span class="money"> ¥{{ currentPlanRow.invoiceAmount }}</span>
          </div>
        </div>
        <!-- <div class="info" v-if="detailData.reconciliationName">
          对账人姓名/电话：{{ detailData.reconciliationName }} {{ detailData.reconciliationMobile }}
        </div> -->
      </div>
      <div class="timeline-wrap">
        <el-timeline class="timeline" style="margin-top: 20px">
          <el-timeline-item v-for="(item, index) in currentPlanRow.payPlanList" :key="index">
            <template #dot>
              <div class="dot">{{ item.collectionType }}期款项</div>
            </template>
            <template #default>
              <div class="default-wrap">
                <div class="default">
                  <div class="default-title">
                    <p>{{ filterBusiness(item.businessNode) }}</p>
                  </div>
                  <el-descriptions class="descriptions" :column="4">
                    <el-descriptions-item label="商家付款比例" label-class-name="my-label" class-name="my-content">
                      {{ item.collectionScale }}%
                    </el-descriptions-item>
                    <el-descriptions-item label="供应商收款节点" label-class-name="my-label" class-name="my-content">
                      {{ filterCollection(item.collectionNode) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="平台支付时效" label-class-name="my-label" class-name="my-content">
                      {{ item.collectionCycle }}
                    </el-descriptions-item>
                    <el-descriptions-item label="计划付款日期" label-class-name="my-label" class-name="my-content">
                      {{ item.planPaymentTime }}
                    </el-descriptions-item>
                    <el-descriptions-item label="付款节点日期" label-class-name="my-label" class-name="my-content">
                      {{ item.paymentTime }}
                    </el-descriptions-item>
                    <el-descriptions-item label="计划应付金额" label-class-name="my-label" class-name="my-content">
                      {{ item.payableAmount }}
                    </el-descriptions-item>
                    <el-descriptions-item label="税额" label-class-name="my-label" class-name="my-content">
                      {{ item.taxAmount }}
                    </el-descriptions-item>
                    <el-descriptions-item label="实际应付金额" label-class-name="my-label" class-name="my-content">
                      {{ item.realityPayableAmount }}
                    </el-descriptions-item>
                    <el-descriptions-item label="剩余应付金额" label-class-name="my-label" class-name="my-content">
                      {{ item.surplusPayableAmount }}
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
              </div>
            </template>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
// 资源导入
import { reactive, onMounted, ref } from "vue";
import { Search, RefreshLeft } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
// 导入api
import {
  getProcureList,
  listByTenantId,
  getCreateInfoList,
  closPurchaseOrderId,
  cancelOrder,
  getFinishConfirm,
  commitConfirm,
  cgOrderDownload
} from "@/apis/procure/index";
import { useRouter, useRoute } from "vue-router";
import RemarkEditor from "@/components/RemarkEditor";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";
import EditorDialog from "./components/editorDialogNew.vue";
import RefuseDialog from "./components/refuseDialog.vue";

const useRoutr = useRouter();
const route = useRoute();
const timerDate = ref();
const formRef = ref();
const _isOpenDel = ref(false); //撤销 二次确认弹窗
const currCelObj = ref({}); //点击撤销的row
const data = reactive({
  slectValue: "1",
  tableData: [],
  list: [], //列表数据
  page: {
    page: 1,
    size: 10
  },
  total: 0,
  forms: {},
  businessStateList: [
    { label: "编辑中", value: 1 },
    { label: "待接单", value: 2 },
    { label: "已拒绝订单", value: 3 },
    { label: "待发货", value: 4 },
    { label: "部分待入库", value: 5 },
    { label: "待入库", value: 6 },
    { label: "部分入库", value: 7 },
    { label: "已入库", value: 8 },
    { label: "已关闭", value: 9 },
    { label: "部分发货", value: 10 },
    { label: "已撤销", value: 20 },
    { label: "撤销待审核", value: 21 }
  ],
  payStatusList: [
    { label: "待支付", value: 1 },
    { label: "部分支付", value: 2 },
    { label: "已支付", value: 3 }
  ],
  priceStatusList: [
    { label: "应付金额", value: 1 },
    { label: "实付金额", value: 2 },
    { label: "商品总计金额", value: 3 },
    { label: "本次应付金额", value: 4 }
  ],
  listByTenantIdList: [],
  createIdList: []
});
import { shoppingList } from "@/store/index";
const shoppingLists = shoppingList();

const editorDialogInfo = ref({});
const _isOpenEditor = ref(false);
const currentRow = ref({});
const downloadLoading = ref(false);

const clickDdownload = () => {
  downloadLoading.value = true;

  let objs = JSON.stringify(data.forms);
  const newObj = JSON.parse(objs);
  newObj.createStartTime = newObj.createTime === undefined ? "" : newObj.createTime[0].split(" ")[0] + " 00:00:00";
  newObj.createEndTime = newObj.createTime === undefined ? "" : newObj.createTime[1].split(" ")[0] + " 23:59:59";
  newObj.expectedDeliveryStartTime =
    newObj.expectedDeliveryTime === undefined ? "" : newObj.expectedDeliveryTime[0].split(" ")[0] + " 00:00:00";
  newObj.expectedDeliveryEndTime =
    newObj.expectedDeliveryTime === undefined ? "" : newObj.expectedDeliveryTime[1].split(" ")[0] + " 23:59:59";
  delete newObj.createTime;
  delete newObj.expectedDeliveryTime;
  let obj = {
    ...data.page,
    ...newObj
  };

  cgOrderDownload(obj).then(res => {
    let url = window.URL.createObjectURL(res);
    const a = document.createElement("a");
    a.href = url;
    a.download = "采购单.xlsx";
    a.click();
    URL.revokeObjectURL(url);
    downloadLoading.value = false;
  });
};

// 业务流程操作类别
const operationFlowType = ref(0);

const handleProduction = (item, type) => {
  currentRow.value = item;
  operationFlowType.value = type;
  getFinishConfirmApi();
};
const isPaymentVisible = row => {
  const validBusinessStates = [4, 5, 6, 7, 8, 23, 24];
  return row.payStatus === 1 && validBusinessStates.includes(row.businessState);
};
// 获取完成确认信息
const getFinishConfirmApi = async () => {
  const res = await getFinishConfirm({ purchaseOrderId: currentRow.value.purchaseOrderId, type: operationFlowType.value });
  editorDialogInfo.value = res.data;
  switch (operationFlowType.value) {
    case 1:
      editorDialogInfo.value.title = "发货确认";
      refuseOptions.value = ["没有技照要求生产", "只完成了部份生产", "没有生产完成", "虚假提交生产完成确认", "其他原因"];
      break;
    case 2:
      editorDialogInfo.value.title = "配送完成确认";
      refuseOptions.value = ["没有按照地址配送", "没有收到商品", "收到部分商品", "虚假提交配送完成", "其他原因"];
      break;
    case 3:
      editorDialogInfo.value.title = "自提货完成确认";
      refuseOptions.value = ["只提取部分产品货物", "没有提货", "货物还没有达到", "虚假提交提货确认", "其他原因"];
      break;
    case 4:
      editorDialogInfo.value.title = "安装完成确认";
      refuseOptions.value = ["没有完成安装", "部分安装", "全部没有安装", "虚假提交安装完成确认", "其他原因"];
      break;
    default:
      break;
  }
  editorDialogInfo.value.titleTips = "等待确认审核";
  editorDialogInfo.value.submitBtnText = "通过";
  editorDialogInfo.value.cancelBtnText = "拒绝";
  _isOpenEditor.value = true;
};

//确认撤销
const returnSubmitDel = () => {
  cancelOrder({ purchaseOrderId: currCelObj.value.purchaseOrderId }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "订单撤销成功",
        type: "success"
      });
      _isOpenDel.value = false;
      handelClickSerch(); //刷新列表
    }
  });
};

// 新建采购单
const handelClickNewAdd = () => {
  shoppingLists.list = [];
  shoppingLists.productInformation.forms = {};
  shoppingLists.productInformation.informationObj = {};
  shoppingLists.productInformation.warehouseList = {};
  shoppingLists.productInformation.warehouseObj = {};
  useRoutr.push({
    path: "/procure/purchase-order/detail",
    query: {
      num: 1 //1为新建，2为详情查看
    }
  });
};
// 查询
const handelClickSerch = () => {
  getList();
};
// 获取表格列表数据
const getList = async () => {
  let objs = JSON.stringify(data.forms);
  const newObj = JSON.parse(objs);
  newObj.createStartTime = newObj.createTime === undefined ? "" : newObj.createTime[0].split(" ")[0] + " 00:00:00";
  newObj.createEndTime = newObj.createTime === undefined ? "" : newObj.createTime[1].split(" ")[0] + " 23:59:59";
  newObj.expectedDeliveryStartTime =
    newObj.expectedDeliveryTime === undefined ? "" : newObj.expectedDeliveryTime[0].split(" ")[0] + " 00:00:00";
  newObj.expectedDeliveryEndTime =
    newObj.expectedDeliveryTime === undefined ? "" : newObj.expectedDeliveryTime[1].split(" ")[0] + " 23:59:59";
  delete newObj.createTime;
  delete newObj.expectedDeliveryTime;
  console.log(data.forms, newObj, "-----------");
  let obj = {
    ...data.page,
    ...newObj
  };
  await getProcureList(obj)
    .then(res => {
      console.log(res);
      if (res.code === 200) {
        data.list = res.data.records;
        data.total = res.data.total;
      }
    })
    .catch(err => {
      console.log(err);
    });
};
// 获取仓库下拉框数据
const listByTenantIds = () => {
  listByTenantId().then(res => {
    console.log(res);
    let arr = [];
    res.data.map(it => {
      arr.push({ label: it.warehouseName, value: it.warehouseId });
    });
    data.listByTenantIdList = arr;
    console.log(data.listByTenantIdList);
  });
};
// 获取今天时间
const handelClickToday = n => {
  if (n === 1) {
    const todaty = publickGetDate(1);

    let time1 = todaty[0].split(" ");

    time1[1] = "00:00:00";
    const t1 = time1.join(" ");
    let time2 = todaty[0].split(" ");

    time2[1] = "23:59:59";
    const t2 = time2.join(" ");
    data.forms.createTime = [t1, t2];
  } else {
    const todaty = publickGetDate(1);

    let time1 = todaty[0].split(" ");

    time1[1] = "00:00:00";
    const t1 = time1.join(" ");
    let time2 = todaty[0].split(" ");

    time2[1] = "23:59:59";
    const t2 = time2.join(" ");
    data.forms.expectedDeliveryTime = [t1, t2];
  }
};
// 获取近7天时间
const handelClickSevenDay = n => {
  const todaty = publickGetDate(7);
  if (n === 1) {
    data.forms.createTime = [todaty[0], todaty[todaty.length - 1]].flat();
  } else {
    data.forms.expectedDeliveryTime = [todaty[0], todaty[todaty.length - 1]].flat();
  }
};
// 获取昨天时间
const handelClickYersToday = n => {
  const date = new Date();
  let y = date.getFullYear();
  let m = date.getMonth() + 1;
  let d = date.getDate();
  if (m < 10) {
    m = "0" + m;
  }
  let dates = y + "-" + m + "-" + (Number(d - 1) < 10 ? "0" : "") + Number(d - 1) + " " + "00:00:00";
  let dates1 = y + "-" + m + "-" + (Number(d - 1) < 10 ? "0" : "") + Number(d - 1) + " " + "23:59:59";
  if (n === 1) {
    data.forms.createTime = [dates, dates1].flat();
  } else {
    data.forms.expectedDeliveryTime = [dates, dates1].flat();
  }
};
// 算日期公用方法
const publickGetDate = num => {
  timerDate.value = [];
  let dates = [];

  let currentDate = new Date(); // 获取当前日期

  // 从当前日期开始，向前推num天
  for (let i = 0; i < num; i++) {
    dates.unshift(new Date(currentDate)); // 将当前日期添加到数组的开始
    currentDate.setDate(currentDate.getDate() - 1); // 将日期向前推一天
  }

  let timeArr = []; // 最终的日期
  // 格式化日期并打印（可选）
  dates.forEach(date => {
    let year = date.getFullYear();
    let month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，所以需要+1，并且使用padStart来确保是两位数
    let day = String(date.getDate()).padStart(2, "0"); // 使用padStart来确保日期是两位数
    // console.log(`${year}-${month}-${day}`);
    timeArr.push(`${year}-${month}-${day} '12:00:00'`);
  });
  return timeArr;
};
// 获取创建人
const getCreateInfoLists = () => {
  let arr = [];
  getCreateInfoList().then(res => {
    console.log(res, "vvvvvvvv");
    res.data.map(it => {
      arr.push({ label: it.nickName, value: it.createId });
    });
    data.createIdList = arr;
  });
};
// 重置
const resetForm = formEl => {
  if (!formEl) return;
  data.forms = {};
  formRef.value.resetFields();
  getList();
};

// 操作栏相关事件
const handelClickCloseOder = item => {
  closPurchaseOrderId(item.purchaseOrderId).then(res => {
    console.log(res);
    if (res.code === 200) {
      ElMessage({
        type: "success",
        message: "关闭成功"
      });
      getList();
    }
  });
};
const handleClickDetail = item => {
  //采购单清单详情
  const routeUrl = useRoutr.resolve({
    path: "/procure/purchase-order/laundry",
    query: {
      purchaseOrderId: item.purchaseOrderId
    }
  });
  window.open(routeUrl.href, "_blank");
};
const handleClickDetails = item => {
  console.log();
  useRoutr.push({
    path: "/procure/purchase-order/close-refuse-oder",
    query: {
      purchaseOrderId: item.purchaseOrderId
    }
  });
};
function goToPath(id, status, path) {
  const _code = route.query.code;
  if (_code) {
    // 地址栏有code时，不打开新页签（避免被谷歌浏览器拦截）
    useRoutr.push({
      path: path,
      query: {
        purchaseOrderId: id,
        businessState: status,
        auto: true
      }
    });
  } else {
    //打开新页签
    const routeUrl = useRoutr.resolve({
      path: path,
      query: {
        purchaseOrderId: id,
        businessState: status
      }
    });
    window.open(routeUrl.href, "_blank");
  }
}
const handelClickChange = item => {
  console.log(item.businessState);
  // return
  switch (item.businessState) {
    case 0:
      break;
    case 1:
      // 编辑中
      goToPath(item.purchaseOrderId, item.businessState, "/procure/purchase-order/refuse-order");
      break;
    case 2:
      goToPath(item.purchaseOrderId, item.businessState, "/procure/purchase-order/close-refuse-oder");
      break;
    case 3:
      // 已拒绝
      goToPath(item.purchaseOrderId, item.businessState, "/procure/purchase-order/refuse-order");
      break;
    case 4:
      goToPath(item.purchaseOrderId, item.businessState, "/procure/purchase-order/close-refuse-oder");
      break;
    case 5:
      goToPath(item.purchaseOrderId, item.businessState, "/procure/purchase-order/close-refuse-oder");
      break;
    case 6:
      goToPath(item.purchaseOrderId, item.businessState, "/procure/purchase-order/close-refuse-oder");
      break;
    case 7:
      goToPath(item.purchaseOrderId, item.businessState, "/procure/purchase-order/close-refuse-oder");
      break;
    case 8:
      goToPath(item.purchaseOrderId, item.businessState, "/procure/purchase-order/close-refuse-oder");
      break;
    case 9:
      goToPath(item.purchaseOrderId, item.businessState, "/procure/purchase-order/close-refuse-oder");
      break;
    case 10:
      goToPath(item.purchaseOrderId, item.businessState, "/procure/purchase-order/close-refuse-oder");
      break;
    case 20:
      goToPath(item.purchaseOrderId, item.businessState, "/procure/purchase-order/close-refuse-oder");
      break;
    case 21:
      goToPath(item.purchaseOrderId, item.businessState, "/procure/purchase-order/close-refuse-oder");
      break;
  }
  // useRoutr.push({
  //   path: "/procure/purchase-order/detail",
  //   query: {
  //     num: 3, //1为新建，2为详情查看
  //     purchaseOrderId: item.purchaseOrderId,
  //     businessState: item.businessState
  //   }
  // });
};
// 显示状态
const showStatus = n => {
  switch (n) {
    case 0:
      return "定时中";
    case 1:
      return "编辑中";
    case 2:
      return "待接单";
    case 3:
      return "已拒绝订单";
    case 4:
      return "待发货";
    case 5:
      return "部分待入库";
    case 6:
      return "待入库";
    case 7:
      return "部分入库";
    case 8:
      return "已入库";
    case 9:
      return "已关闭";
    case 10:
      return "部分发货";
    case 20:
      return "已撤销";
    case 21:
      return "撤销待审核";
    default:
      "";
  }
};
const statusColor = n => {
  switch (n) {
    case 0:
      return "#606266";
    case 1:
      return "#606266";
    case 2:
      return "#FF9900";
    case 3:
      return "#FF3333";
    case 4:
      return "#FF9900";
    case 5:
      return "#007DFF";
    case 6:
      return "#FF9900";
    case 7:
      return "#007DFF";
    case 8:
      return "#007DFF";
    case 9:
      return "#86909C";
    case 10:
      return "#007DFF";
    case 20:
      return "#ff3333";
    case 21:
      return "#FF9900"; //黄色
    default:
      "";
  }
};
const payStatusColor = n => {
  switch (n) {
    case 1:
      return ["#FF9900", "#FFF0D9"];
    case 2:
      return ["#007DFF", "#D9EDFF"];
    case 3:
      return ["#14C85C", "#E3F9E9"];
    default:
      "";
  }
};
// 分页事件
const handleSizeChange = v => {
  data.page.size = v;
  getList();
};
const handleCurrentChange = v => {
  data.page.page = v;
  getList();
};
onMounted(async () => {
  const _code = route.query.code;
  if (_code) {
    data.forms["purchaseOrderNo"] = _code;

    await getList();
    if (data.list.length > 0) {
      handelClickChange(data.list[0]);
      return;
    }
  }
  getList();
  listByTenantIds();
  getCreateInfoLists();
});

// 通过审核二次确认-弹窗
const adoptDialog = ref(false);
const adoptDialogSubmit = async () => {
  await commitConfirmApi(1);
  adoptDialog.value = false;
  closeDrawer();
};

// 拒绝-弹窗
const refuseDialog = ref(false);
// 拒绝原因
const refuseOptions = ref([]);
// 拒绝弹窗-提交
const refuseSubmit = async value => {
  await commitConfirmApi(0, value.refuseReason, value.refuseRemark);
  await getFinishConfirmApi();
  refuseClose();
};
const refuseClose = () => {
  refuseDialog.value = false;
};

// 抽屉
// 生产完成确认、已完成提货、安装完成确认、配送完成确认
// 抽屉-通过
const submitDrawer = () => {
  adoptDialog.value = true;
};
// 抽屉-拒绝
const refuseDrawer = () => {
  refuseDialog.value = true;
};
// 抽屉-关闭
const closeDrawer = () => {
  _isOpenEditor.value = false;
};

// 提交完成确认信息
const commitConfirmApi = async (opinion, refuseReason, refuseRemark) => {
  await commitConfirm({
    purchaseOrderId: currentRow.value.purchaseOrderId,
    type: operationFlowType.value,
    opinion,
    refuseReason,
    refuseRemark
  }).then(() => {
    if (opinion == 1) {
      ElMessage.success("审核通过");
    }
    getList();
  });
};

// 付款计划节点明细-弹窗
const planNodes = ref(false);
const currentPlanRow = ref({});
const openPlanNodes = row => {
  currentPlanRow.value = row;
  planNodes.value = true;
};

const filterCollection = value => {
  let name = "";
  switch (value) {
    case 1:
      name = "接采购单即付款";
      break;
    case 2:
      name = "生产完成确认";
      break;
    case 3:
      name = "发货完成";
      break;
    case 4:
      name = "入库确认";
      break;
    case 5:
      name = "配送完成确认";
      break;
    case 6:
      name = "安装完成确认";
      break;
    default:
      name = "-";
      break;
  }
  return name;
};

const filterBusiness = value => {
  let name = "";
  switch (value) {
    case 1:
      name = "节点付款";
      break;
    case 2:
      name = "生产完成确认";
      break;
    case 3:
      name = "已发货";
      break;
    case 4:
      name = "入库完成";
      break;
    case 5:
      name = "配送完成";
      break;
    case 6:
      name = "安装完成";
      break;
    default:
      name = "-";
      break;
  }
  return name;
};
</script>
<style scoped lang="scss">
@import "./index.scss";
.dd-price-wrap {
  width: 100%;
  display: flex;
  align-items: center;
  :deep(.el-select) {
    width: 200px;
  }
  .price-range {
    flex: 1;
    display: flex;
    align-items: center;
    margin-left: 10px;
  }
}
.adopt-dialog {
  text-align: center;
  margin-top: 20px;
  margin-bottom: 35px;
  line-height: 22px;
}
</style>
